package com.hmsg.health.utils;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZIPUtil {

	private static final String CHARSET = "UTF-8";

	private GZIPUtil() {
	}

	/**
	 * 压缩字符串
	 * 
	 * @param str
	 * @return
	 */
	public static String compressToStr(String str) {
		return new String(compress(str));
	}

	public static byte[] compress(String str) {
		try {
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream);

			byte[] bytes = str.getBytes(CHARSET);
			gzipOutputStream.write(bytes, 0, bytes.length);
			gzipOutputStream.finish();
			gzipOutputStream.flush();
			gzipOutputStream.close();

			return byteArrayOutputStream.toByteArray();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static String decompress(byte[] bytes) {
		try {
			GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(bytes));
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(gzipInputStream, CHARSET));

			StringBuffer content = new StringBuffer();
			String line;
			while ((line = bufferedReader.readLine()) != null) {
				content.append(line);
			}

			return content.toString();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}
